package com.lst.common;

import java.util.Date;

import org.apache.log4j.Logger;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

import com.lst.common.JPushEnum;
import com.lst.model.MstMessage;
import com.lst.utils.DateUtil;


/**
 * @ClassName: JPushMessage
 * @Description: 极光推送
 * @author zmm
 * @date 2017年10月28日上午11:57:08
 *
 */
public class JPushMessage {
	private static Logger logger = Logger.getLogger("log");
	/**
	 * 
	 * @Title: buildPushObject_all_all_alert
	 * @Description:所有平台，所有设备，内容为 content 的通知
	 * @param @param reqPara
	 * @param @return    设定文件
	 * @return PushPayload    返回类型
	 * @throws
	 */
	public static PushPayload buildPushObject_all_all_alert(MstMessage message) {
		return PushPayload.alertAll(message.getContent());
	}


	/**
	 * 
	 * @Title: buildPushObject_all_alias_alert
	 * @Description: 所有平台，推送目标是别名为 "alias1"，通知内容为  content
	 * @param @param reqPara
	 * @param @return    设定文件
	 * @return PushPayload    返回类型    .setNotification(Notification.alert(message.getReserved12()+message.getContent()))
	 * @throws
	 */
	public static PushPayload buildPushObject_all_alias_alert(MstMessage message) {
		return PushPayload.newBuilder()
				.setPlatform(Platform.all())
				.setOptions(Options.newBuilder().setApnsProduction(true).build())
				.setAudience(Audience.alias(CommCode.JPUSH_ALIAS_ANYONE + message.getReceiveid()))
				.setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(message.getReserved12()+message.getContent())
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .incrBadge(1)
                                .setSound("happy")
                                .addExtra("msgId",message.getId())
                                .setAlert(message.getReserved12()+message.getContent())
                                .build())
                        .build())
				.build();
	}
	
	public static PushPayload buildPushObject_all_alias_alert2(MstMessage message) {
		return PushPayload.newBuilder()
				.setPlatform(Platform.all())
				.setOptions(Options.newBuilder().setApnsProduction(true).build())
				.setAudience(Audience.alias(CommCode.JPUSH_ALIAS_ANYONE + message.getReceiveid()))
				.setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(message.getContent())
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .incrBadge(1)
                                .setSound("happy")
                                .addExtra("msgId",message.getId())
                                .setAlert(message.getContent())
                                .build())
                        .build())
				.build();
	}



	/**
	 * 
	 * @Title: buildPushObject_android_tag_alertWithTitle
	 * @Description: 平台是 Android，目标是 tag 为 "tag1" 的设备，内容是 【这是内容】，并且标题为 【这是标题】。
	 * @param @return    设定文件
	 * @return PushPayload    返回类型
	 * @throws
	 */
	public static PushPayload buildPushObject_android_alias_alertWithTitle(MstMessage message) {
		return PushPayload.newBuilder()
				.setPlatform(Platform.android())
				.setAudience(Audience.alias(CommCode.JPUSH_ALIAS_ANYONE + message.getReceiveid()))
				.setNotification(Notification.android(message.getContent(), message.getContent(), null))
				.build();
	}
	//构建推送对象：平台是 iOS，推送目标是 "tag1", 
	//"tag_all" 的交集，推送内容同时包括通知与消息 - 通知信息是 ALERT，角标数字为 5，
	//通知声音为 "happy"，并且附加字段 from = "JPush"；消息内容是 MSG_CONTENT。
	//通知是 APNs 推送通道的，消息是 JPush 应用内消息通道的。
	//APNs 的推送环境是“生产”（如果不显式设置的话，Library 会默认指定为开发）
	public static PushPayload buildPushObject_ios_alias_alertWithExtrasAndMessage(MstMessage message) {
		return PushPayload.newBuilder()
				.setPlatform(Platform.ios())
				.setAudience(Audience.alias(CommCode.JPUSH_ALIAS_ANYONE + message.getReceiveid()))
				.setNotification(Notification.newBuilder()
						.addPlatformNotification(IosNotification.newBuilder()
								.setAlert(message.getContent())
								.setBadge(+1)
								.setSound("happy")
								.addExtra("from", "JPush")
								.build())
								.build())
								.setMessage(Message.content(message.getContent()))
								.setOptions(Options.newBuilder()
										.setApnsProduction(true)
										.build())
										.build();
	}
	/**
	 * 
	 * @Title: pushMessage
	 * @Description:实现消息推送
	 * @param @param message
	 * @param @param type
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public static String pushMessage(MstMessage message, JPushEnum type){
		Date startDate = new Date();
		logger.info("JPushMessage pushMessage start:" + startDate);

		String masterSecret = "285bc16c5a050c8714fb44bd";
		String appKey = "e5a2cdb03ae375d12564ae3d";
		
		 ClientConfig clientConfig = ClientConfig.getInstance();
		 JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
		 PushPayload payload = null;
		 String msg = ""; 

		if(type.equals(JPushEnum.ALL_ALIAS)){
			payload = buildPushObject_all_alias_alert(message);
		}else if(type.equals(JPushEnum.ALL_ALL)){
			payload = buildPushObject_all_all_alert(message);
		}else if(type.equals(JPushEnum.ANDROID_ALIAS)){
			payload = buildPushObject_android_alias_alertWithTitle(message);
		}else if(type.equals(JPushEnum.IOS_ALIAS)){
			payload = buildPushObject_ios_alias_alertWithExtrasAndMessage(message);
		}else{
			msg =  "推送方式不对";
		}

		try {
			PushResult result = jpushClient.sendPush(payload);
			logger.info(result);
			msg = "right";
		} catch (APIConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (APIRequestException e) {
			logger.info("JPushMessage pushMessage Should review the error, and fix the request"+ e);
			logger.info("JPushMessage pushMessage HTTP Status: " + e.getStatus());
			logger.info("JPushMessage pushMessage Error Code: " + e.getErrorCode());
			logger.info("JPushMessage pushMessage Error Message: " + e.getErrorMessage());
			msg = e.getErrorMessage();
		}


		logger.info("JPushMessage pushMessage end:" + 
				DateUtil.calLastedTime(startDate));

		return msg;
	}
	
	
	public static String pushMessage2(MstMessage message, JPushEnum type){
		Date startDate = new Date();
		logger.info("JPushMessage pushMessage start:" + startDate);

		String masterSecret = "285bc16c5a050c8714fb44bd";
		String appKey = "e5a2cdb03ae375d12564ae3d";
		
		 ClientConfig clientConfig = ClientConfig.getInstance();
		 JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
		 PushPayload payload = null;
		 String msg = ""; 

		if(type.equals(JPushEnum.ALL_ALIAS)){
			payload = buildPushObject_all_alias_alert2(message);
		}else if(type.equals(JPushEnum.ALL_ALL)){
			payload = buildPushObject_all_all_alert(message);
		}else if(type.equals(JPushEnum.ANDROID_ALIAS)){
			payload = buildPushObject_android_alias_alertWithTitle(message);
		}else if(type.equals(JPushEnum.IOS_ALIAS)){
			payload = buildPushObject_ios_alias_alertWithExtrasAndMessage(message);
		}
		else{
			msg =  "推送方式不对";
		}

		try {
			PushResult result = jpushClient.sendPush(payload);
			logger.info(result);
			msg = "right";
		} catch (APIConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (APIRequestException e) {
			logger.info("JPushMessage pushMessage Should review the error, and fix the request"+ e);
			logger.info("JPushMessage pushMessage HTTP Status: " + e.getStatus());
			logger.info("JPushMessage pushMessage Error Code: " + e.getErrorCode());
			logger.info("JPushMessage pushMessage Error Message: " + e.getErrorMessage());
			msg = e.getErrorMessage();
		}


		logger.info("JPushMessage pushMessage end:" + 
				DateUtil.calLastedTime(startDate));

		return msg;
	}
	
	public static void main(String[] args) {
		MstMessage message = new MstMessage();
		message.setContent("hello ,today is sunday!");
	//	message.setReceiveid(647);
		pushMessage(message, JPushEnum.ALL_ALIAS);
	
	}

}
